package org.dreamwork.jasmine2.web.controls.datagrid;

import org.dreamwork.peony.DataBinder;
import org.dreamwork.util.StringUtil;

import java.util.Comparator;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-10-15
 * Time: 10:28:23
 */
public class DefaultComparetor implements Comparator<Object> {
    private String field;

    public DefaultComparetor (String field) {
        this.field = field;
    }

    @SuppressWarnings ("unchecked")
    public int compare (Object o1, Object o2) {
        if (StringUtil.isEmpty (field))
            return compareObject (o1, o2);
        Object v1 = DataBinder.eval (o1, field);
        Object v2 = DataBinder.eval (o2, field);
        if (v1 instanceof Comparable) return ((Comparable) v1).compareTo (v2);
        return compareObject (v1, v2); 
    }

    private int compareObject (Object o1, Object o2) {
        if (o1 == null && o2 == null) return 0;
        if (o1 == null) return -1;
        if (o2 == null) return 1;
        return o1.hashCode () - o2.hashCode ();
    }
}